from django.shortcuts import render
from rest_framework.generics import ListAPIView,CreateAPIView, UpdateAPIView,DestroyAPIView
from rest_framework.response import Response
from rest_framework_extensions.cache.decorators import cache_response

from areas.models import Area
from areas.serializers import AreasSerializer, AddressSerializer
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from users.models import Address

# Create your views here.
class AreasView(CacheResponseMixin,ListAPIView):
    '''
        返回省数据
    '''
    serializer_class = AreasSerializer
    queryset = Area.objects.filter(parent=None)
    pagination_class = None


class AreaView(ListAPIView):
    '''
        返回市县数据
    '''
    serializer_class = AreasSerializer
    # queryset = Area.objects.filter(parent_id = pk)
    pagination_class = None
    def get_queryset(self):
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)


class AddressView(CreateAPIView,UpdateAPIView,ListAPIView):
    '''
        保存用户地址
    '''
    serializer_class = AddressSerializer
    pagination_class = None

    # queryset = Address.objects.filter()
    # is_deleted = false不指定逻辑删除
    def get_queryset(self):
        return Address.objects.filter(user = self.request.user, is_deleted = False)

    def delete(self, request, *args, **kwargs):

        obj = self.get_object()

        obj.is_deleted = True
        obj.save()

        return Response()


    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response({'addresses':serializer.data,
                         'default_address_id':self.request.user.default_address_id})


